# Detention as a Peacemaking Strategy: The 2007-08 Iraq Surge and US Detention
# R Batch File to make figures
# Author: Spencer L Willardson
# R Version 3.1.3
# Date: 14 August 2015

# ABOUT: This file makes the three figures used in the Foreign Policy Analysis Paper.  This batch file can be run to make the figures.

# Instructions: Fill in the setwd("") field below to the location of the folder containing the batch fileand the data. If you are using Rstudio and open the analysis.R script, this should be the working directory already.  Uncomment the line and run the file in R (I use Rstudio, but R standalone will work).  The figures will output as .png files.


# Generate Figure 1 for paper.
# setwd("")
detainee <- read.csv("iraq_detainee_indicators.csv")

# get rid of first line of data, since it is mostly missing and can cause some problems:
detainee = detainee[-1,]

meandet <- mean(detainee$total.detainees)
# Now Plot
pdf("fig1.pdf")

plot(detainee$total.detainees, type= "l", main= "Number of Iraqi Detainees in Custody by Month \n 2003-2008",
     ylab = "Detainees in Custody at End of Month", xlab=NA, xaxt="n")
axis(1, at=1:65, labels=detainee$label, cex.axis=1.25)
abline(h = meandet, lty=2)
abline(v=48, lty=3)
text(11, meandet+900, "Mean Number of Detainees")
text(49, 7000, "Surge Announced", srt=90, cex=0.8)
mtext(side = 1, "April 2003-August 2008", line = 3)
dev.off()

# Generate Figure 2 - Civilian Casualties
civilian <- detainee
civilian = civilian[-1,]
meandeath <- mean(civilian$iraqi.civ.death)
pdf("fig2.pdf")

plot(civilian$iraqi.civ.death, type= "l", main= "Iraqi Civilian Deaths by Month \n 2003-2008",
     ylab = "Iraqi Civilian Casualties by Month", xlab=NA, xaxt="n")
axis(1, at=1:64, labels=civilian$label, cex.axis=1.25)
abline(h = meandeath, lty=2)
#abline(v=48, lty=3)
text(10, meandeath+200, "Mean Number of Civilian Deaths", cex=0.75)
points(34, 1570, pch=19)
text(34, 1570, "Golden Mosque Bombed", cex=0.75, pos=4)
points(46, 2674, pch=19)
text(45, 2620, "Surge Announced", cex=0.75, pos=1)

mtext(side = 1, "May 2003-August 2008", line = 3)
dev.off()


# Ratio of Sunni to Shia detained
detainee$ratio <- detainee$sunni/(detainee$shia+1)
detainee1 <- detainee
for(i in 1:9){
detainee1 <- detainee1[-1,]
}

sub1 <- subset(detainee1, detainee1$id<565)
mean1 <- mean(sub1$ratio)
sub2 <- subset(detainee1, detainee1$id>564)
mean2 <- mean(sub2$ratio)

# Plot figure 3

pdf("fig3.pdf")
plot(detainee1$ratio, type="l", main= "Ratio of Sunni to Shia Detained by Month \n 2004-2008",
     ylab = "Ratio Sunni/Shia", xlab=NA, xaxt="n")

axis(1, at=1:56, labels=detainee1$label, cex.axis=1.25)
mtext(side = 1, "January2004 - August 2008", line = 3)
segments(1, mean1, 37, mean1, lty=3)
segments(38, mean2, 56, mean2, lty=3)
text(10, mean1+1, "Mean Value of Ratio pre-Surge", cex=0.75)
text(46, mean2+1, "Mean Value of Ratio post-Surge", cex=0.75)
dev.off()
